package cn.wolfcode.luowowo.controller;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.domain.*;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.ParamMap;
import cn.wolfcode.luowowo.util.UMEditorUploader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/travel")
public class TravelController {

    @Autowired
    private ITravelService travelService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ITravelCommentService travelCommentService;

    //自定义参数解析器测试
    @GetMapping("/info")
    public Object info(@UserParam UserInfo userInfo) {
        System.err.println(userInfo);
        return JsonResult.success(userInfo);
    }

    //游记分页
    @GetMapping("/query")
    public Object query(TravelQuery qo) {
        //分页
        Page<Travel> page = travelService.query(qo);
        return JsonResult.success(page);
    }

    //编辑
    @GetMapping("/input")
    public Object input(String id) {
        ParamMap map = new ParamMap();
        //map.tv
        if (StringUtils.hasLength(id)) {
            Travel travel = travelService.get(id);
            map.put("tv", travel);
        }
        //map.dests;
        List<Destination> dests = destinationService.list();
        map.put("dests", dests);
        return JsonResult.success(map);
    }

    //游记详情
    @GetMapping("/detail")
    public Object detail(String id) {
        // vue.detail = map.detail;
        Travel travel = travelService.get(id);

        // vue.toasts = map.toasts;
        //查询当前篇游记的目的地， 关联查询目的地的父目的地， 显示当前目的地的封面与名称
        List<Destination> toasts = destinationService.getToasts(travel.getDestId());

        // vue.strategies = map.strategies;
        //根据当前篇游记的目的地查询该目的地下阅读量为前3的攻略，循环播放
        List<Strategy> strategies = strategyService.getViewnumTop3(travel.getDestId());

        // vue.travels = map.travels;
        //根据当前篇游记的目的地查询该目的地下阅读量为前3的游记，循环播放
        List<Travel> travels = travelService.getViewnumTop3(travel.getDestId());

        // vue.page = map.page;   评论分页
        //评论的点赞要分页
        //查询评论数据，一页显示
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);//一页显示所有数据21亿条
        Page<TravelComment> page = travelCommentService.query(qo);


        return JsonResult.success(new ParamMap()
                .put("detail", travel)
                .put("toasts",toasts )
                .put("strategies",strategies )
                .put("travels", travels)
                .put("page", page)
        );
    }


    //保存或者修改
    @PostMapping("/saveOrUpdate")
    @RequireLogin  //这个方法只能是登录的用户才能操作，所以用登录拦截器来限制未登录用户的操作
    public Object saveOrUpdate(Travel travel, HttpServletRequest request) {
        //保存修改操作只能登录后才能操作，需要在表现层验证用户是否登录
        //获得当前登录的用户信息,通过令牌token
        String token = request.getHeader("token");
        //判断用户是否登录
        UserInfo user = userInfoRedisService.getUserInfoByToken(token);
        if (user != null) {
            travel.setUserId(user.getId());
        }

        //最新刚刚保存/修改的游记的id
        String id = travelService.saveOrUpdate(travel);
        return JsonResult.success(id);
    }

    //游记评论
    @PostMapping("/commentAdd")
    @RequireLogin  //这个方法只能是登录的用户才能操作，所以用登录拦截器来限制未登录用户的操作
    public Object commentAdd(TravelComment comment, @UserParam UserInfo userInfo) {

        //用户游记评论
        BeanUtils.copyProperties(userInfo, comment);
        comment.setUserId(userInfo.getId());
        travelCommentService.addComment(comment);

        //查询评论数据，一页显示
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(comment.getTravelId());
        qo.setPageSize(Integer.MAX_VALUE);//一页显示所有数据21亿条
        Page<TravelComment> page = travelCommentService.query(qo);

        return JsonResult.success(page);
    }









    //百度的富文本编辑器的上传图片
    @PostMapping("/contentImage")
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }



}
